﻿@model WebApp.Models.SUPPLIER
@{
	ViewBag.Title = "供应商管理";
}
<!-- MAIN CONTENT -->
<div id="content">
    <!-- quick navigation bar -->
    <div class="row">
        <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4">
            <h1 class="page-title txt-color-blueDark">
                <i class="fa fa-table fa-fw "></i>
                主数据管理
                <span>
                    >
                  供应商管理
                </span>
            </h1>
        </div>
        <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8">
            
        </div>
    </div>
    <!-- end quick navigation bar -->
    <!-- widget grid -->
    <section id="widget-grid" class="">
        <!-- row -->
        <div class="row">
            <!-- NEW WIDGET START -->
            <article class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <!-- Widget ID (each widget will need unique ID)-->
                <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false" data-widget-deletebutton="false">
                    <!-- widget options:
                    usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">
                    data-widget-colorbutton="false"
                    data-widget-editbutton="false"
                    data-widget-togglebutton="false"
                    data-widget-deletebutton="false"
                    data-widget-fullscreenbutton="false"
                    data-widget-custombutton="false"
                    data-widget-collapsed="true"
                    data-widget-sortable="false"
                    -->
                    <header>
                        <span class="widget-icon"> <i class="fa fa-table"></i> </span>
                        <h2>供应商管理</h2>
                    </header>

                     <!-- widget div-->
                    <div>
                        <!-- widget edit box -->
                        <div class="jarviswidget-editbox">
                            <!-- This area used as dropdown edit box -->
                        </div>
                        <!-- end widget edit box -->
                        <!-- widget content -->
                        <div class="widget-body no-padding">
                            <div class="sk-spinner sk-spinner-wave">
                              <div class="sk-rect1"></div>
                              <div class="sk-rect2"></div>
                              <div class="sk-rect3"></div>
                              <div class="sk-rect4"></div>
                              <div class="sk-rect5"></div>
                            </div>
                            <div class="widget-body-toolbar">
                                <div class="row">
                                    <div class="col-sm-8  ">
                                        <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="append()" class="btn btn-default"> <i class="fa fa-plus"></i> @Html.L("Add") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="removeit()" class="btn btn-default"> <i class="fa fa-trash-o"></i> @Html.L("Delete") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="accept()" class="btn btn-default"> <i class="fa fa-floppy-o"></i> @Html.L("Save") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="reject()" class="btn btn-default"> <i class="fa fa-ban"></i> @Html.L("Cancel") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="reload()" class="btn btn-default"> <i class="fa fa-refresh"></i> @Html.L("Refresh") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm hidden-xs">
                                            <button type="button" onclick="importexcel()" class="btn btn-default"><i class="fa fa-cloud-upload"></i> @Html.L("Import") </button>
                                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <span class="caret"></span>
                                                <span class="sr-only">Toggle Dropdown</span>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a href="javascript:importexcel()"><i class="fa fa-file-excel-o"></i>  @Html.L("Upload") </a></li>
                                                <li role="separator" class="divider"></li>
                                                <li><a href="javascript:downloadtemplate()"><i class="fa fa-download"></i> @Html.L("Download") </a></li>
                                            </ul>
                                        </div>
                                        <div class="btn-group btn-group-sm hidden-xs hidden-md">
                                            <button onclick="exportexcel()" class="btn btn-default"> <i class="fa fa-file-excel-o"></i> @Html.L("Export") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm visible-lg-inline-block">
                                            <button onclick="print()" class="btn btn-default"> <i class="fa fa-print"></i> @Html.L("Print") </button>
                                        </div>
                                        <div class="btn-group btn-group-sm visible-lg-inline-block">
                                            <button onclick="dohelp()" class="btn btn-default"> <i class="fa fa-question-circle-o"></i> @Html.L("Help") </button>
                                        </div>
                                    </div>
                                    <div class="col-sm-4 text-align-right visible-lg-inline-block">
                                        <div class="btn-group btn-group-sm">
                                            <button onclick="window.history.back()" class="btn btn-sm btn-success"> <i class="fa fa-chevron-left"></i> @Html.L("GoBack") </button>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="alert alert-warning no-margin fade in">
                                <button class="close" data-dismiss="alert">
                                    ×
                                </button>
                                <i class="fa-fw fa fa-info"></i>
                                注意事项:
                            </div>
	                        <!--begin datagrid-content -->
	                        <div class="table-responsive">
		                         <table id="suppliers_datagrid">  
		                         </table>
                    		</div>
		                    <!--end datagrid-content -->
                         </div>
                        <!-- end widget content -->
                    </div>
                    <!-- end widget div -->
                </div>
                <!-- end widget -->
            </article>
            <!-- WIDGET END -->
        </div>
        <!-- end row -->
    </section>
    <!-- end widget grid -->
	<!-- file upload partial view -->
    <!-- RenderPartial() does exactly the same thing and is better for performance over Partial() -->
	@{ Html.RenderPartial("_ImportWindow",new ViewDataDictionary {{ "EntityName","SUPPLIER" }}); }		 
	<!-- end file upload partial view -->
    <!-- detail popup window -->
    @{ Html.RenderPartial("_PopupDetailFormView",new WebApp.Models.SUPPLIER()); }
    <!-- end detail popup window -->
            
</div>
<!-- END MAIN CONTENT -->

@section Scripts {
<script type="text/javascript">
      //是否启用弹窗口模式新增编辑数据
      const POPUPMODE = false;
      //是否强制从后台取值
      const REQUIRBACKEND = false;
      //是否开启行内编辑
      const EDITINLINE = true;
      //上传导入参数设定
      const entityname = "SUPPLIER";
      var supplier = {};
      
      //下载Excel导入模板
      function downloadtemplate() {
          //默认模板路径存放位置
          const url = '/FileUpload/Download?file=/ExcelTemplate/SUPPLIER.xlsx';
          $.fileDownload(url)
           .done(() => {
                    //console.log('file download a success!');
                    toastr.success('模板下载完成!');  
                })
           .fail(() => {
               $.messager.alert('失败','没有下载到导入模板[SUPPLIER.xlsx]文件!','error'); 
            });           
       }
       //打印
       function print() {
            $dg.datagrid('print', 'DataGrid');
       }
        //打开Excel上传窗口
	   function importexcel() {
		    $('#importwindow').window('open');
	   }
	   //执行导出下载Excel
	   function exportexcel() {
				const filterRules = JSON.stringify($dg.datagrid('options').filterRules);
				//console.log(filterRules);
				$.messager.progress({ title: '正在执行导出!' });
				let formData = new FormData();
				formData.append('filterRules', filterRules);
				formData.append('sort', 'ID');
				formData.append('order', 'asc');
				$.postDownload('/SUPPLIERs/ExportExcel', formData).then(res => {
                    $.messager.progress('close');
                    toastr.success('导出成功!');
                }).catch(err => {
                    //console.log(err);
                    $.messager.progress('close');
                    $.messager.alert('失败', err.statusText, 'error');
                });

		}
        //显示帮助信息
        function dohelp() {
            toastr.info('有问题请联系管理员 <br><i class="fa fa-envelope-o" aria-hidden="true"></i> : demo@admin.com','帮助');  
        }
       var editIndex = undefined;
       //重新加载数据
	   function reload() {
			if (endEditing()) {
			    $dg.datagrid('reload');
		    }
	   }
      //关闭编辑状态
	  function endEditing() {
			if (editIndex === undefined) { 
                return true; 
            }
			if ($dg.datagrid('validateRow', editIndex)) {
				$dg.datagrid('endEdit', editIndex);
				editIndex = undefined;
                return true;
			} else {
				const invalidinput = $('input.validatebox-invalid','.datagrid');
                const fieldnames = invalidinput.map((index, item) => {
                  return $(item).attr('placeholder') || $(item).attr('id');
                });
                $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error');
				return false;
			}
		}
    //单击列开启编辑功能
  function onClickCell(index, field) {
    supplier = $dg.datagrid('getRows')[index];
    const _operates = ['_operate1', 'ck'];
    if (!EDITINLINE || $.inArray(field, _operates) >= 0) {
      return;
    }
    if (editIndex !== index) {
      if (endEditing()) {
        $dg.datagrid('selectRow', index)
          .datagrid('beginEdit', index);
        hook = true;
        editIndex = index;
        const ed = $dg.datagrid('getEditor', { index: index, field: field });
        if (ed) {
          ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
        }
      } else {
        $dg.datagrid('selectRow', editIndex);
      }
    }
  }
    //新增记录
  async function append() {
    supplier = {
      SUPPLIERCODE: '-',
      SUPPLIERNAME: '-',
      ISDISABLED: false,
      ADDRESS1: '-',
      ADDRESS2: '-',
    };
    //需要后台创建对象
    if (REQUIRBACKEND) {
      supplier = await $.get('/SUPPLIERs/NewItemAsync');
    }
    if (POPUPMODE) {
      //弹出新增窗口
      opendetailwindow(supplier, 'Added');
    } else {
      if (endEditing()) {
        //对必填字段进行默认值初始化
        $dg.datagrid('insertRow',
          {
            index: 0,
            row: supplier
          });
        editIndex = 0;
        $dg.datagrid('selectRow', editIndex)
          .datagrid('beginEdit', editIndex);
        hook = true;
      }
    }
  }
    //删除编辑的行
	function removeit() {
       if (EDITINLINE) {
          if ($dg.datagrid('getChecked').length > 0) {
            deletechecked();
            return;
          }
          if (editIndex !== undefined) { 
    			$dg.datagrid('cancelEdit', editIndex)
					.datagrid('deleteRow', editIndex);
			   editIndex = undefined;
               hook = true;
           }else{
              const row = $dg.datagrid('getSelected');
              if(row){
                const rowindex = $dg.datagrid('getRowIndex', row);
                $dg.datagrid('deleteRow', rowindex);
                hook = true;
              }else{
                $.messager.alert('提示', '请选中需要删除的记录.', 'info');
              }
           }
        } else {
		   if ($dg.datagrid('getChecked').length > 0) {
              deletechecked();
           }
           else {
              $.messager.alert('提示', '请选中需要删除的记录.', 'info');
           }
        }
	}
    //删除该行
    function deleteRow(id) {
          $.messager.confirm('确认', '你确定要删除该记录?', result => {
                if (result) {
                    $.post('/SUPPLIERs/DeleteCheckedAsync', { id: [id] })
                         .done(response => {
                                if (response.success) {
                                    toastr.success('删除成功');  
                                    $dg.datagrid('uncheckAll');
                                    $dg.datagrid('reload');
                                } else {
                                    $.messager.alert('错误', response.err,'error');
                                }
                          })
                          .fail((jqXHR, textStatus, errorThrown) => {
						        $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
					      });
                    }
                });  
         
     }
    //删除选中的行
    function deletechecked() {
        const rows = $dg.datagrid('getChecked');
        if (rows.length > 0) {
            const id = rows.filter(item=>item.ID!=null).map(item => {
                   return item.ID;
                });
            $.messager.confirm('确认', `你确定要删除这 <span class='badge bg-color-red'>${id.length} </span> 行记录?`, result => {
                if (result) {
                    $.post('/SUPPLIERs/DeleteCheckedAsync', { id: id })
                         .done(response => {
                                if (response.success) {
                                    toastr.success('删除成功');  
                                    $dg.datagrid('uncheckAll');
                                    $dg.datagrid('reload');
                                } else {
                                    $.messager.alert('错误', response.err,'error');
                                }
                          })
                          .fail((jqXHR, textStatus, errorThrown) => {
						     $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
					      });
                    }
                });  
         } else {
                $.messager.alert('提示', '请先选择要删除的记录!','question');
         }
     }
    //提交保存后台数据库
	function accept() {
	  if (endEditing()) {
		if ($dg.datagrid('getChanges').length > 0) {
		  const inserted = $dg.datagrid('getChanges', 'inserted').map(item => {
          item.TrackingState = 1;
          return item;
        });
        const updated = $dg.datagrid('getChanges', 'updated').map(item => {
          item.TrackingState = 2
          return item;
        });
        const deleted = $dg.datagrid('getChanges', 'deleted').map(item => {
          item.TrackingState = 3
          return item;
        });
        //过滤已删除的重复项
        const changed = inserted.concat(updated.filter(item => {
            return !deleted.includes(item);
          })).concat(deleted);
        //console.table(changed);
		$.post('/SUPPLIERs/SaveDataAsync', {suppliers:changed})
                     .done(response => {
						   //console.log(response);
						   if (response.success) {
							   toastr.success('保存成功');  
							   $dg.datagrid('acceptChanges');
							   $dg.datagrid('reload');
                               hook = false;
						   } else {
                               $.messager.alert('错误', response.err ,'error');
                           }
					    })
                      .fail((jqXHR, textStatus, errorThrown) => {
						$.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
					  });
				}
			}
	}
	function reject() {
	    $dg.datagrid('rejectChanges');
	    editIndex = undefined;
        hook = false;
	}
	function getChanges() {
	    const rows = $dg.datagrid('getChanges');
		//console.log(rows.length + ' rows are changed!');
	}
    //弹出明细信息
	async function showDetailsWindow(id,row,index) {
        if (REQUIRBACKEND) {
			//console.log(index, row);
           supplier = await $.get('/SUPPLIERs/GetItemAsync/' + id);
        } else {
            supplier =  $dg.datagrid('getRows')[index];
        }
        opendetailwindow(supplier,'Modified');
	}

    //初始化定义datagrid
    var $dg = $('#suppliers_datagrid');
    $(() => {
		 //定义datagrid结构
         $dg.datagrid({
                        rownumbers:true,
				        checkOnSelect:false,
				        selectOnCheck:false,
				        idField:'ID',
				        sortName:'ID',
				        sortOrder:'desc',
				        remoteFilter: true,
				        singleSelect: true,
                        url: '/SUPPLIERs/GetDataAsync',
				        method: 'get',
				        onClickCell: onClickCell,
				        pagination: true,
                        striped:true,
                        onBeforeLoad: function () {
                           //datagrid resize when jarvisWidgets resized.
                           const that = $(this);
                           $(window).on("resize.jarvisWidgets", () => {
                               that.datagrid('resize');
                           })
                         },
				        onSelect: function(index,row) {
                           supplier = row;
                        },
                        onBeginEdit: function (index, row) {
                          
                         },
                        onEndEdit: function (index, row) {
                          
                         },
                         onBeforeEdit: function (index, row) {
                            row.editing = true;
                            $(this).datagrid('refreshRow', index);
                          },
                          onAfterEdit: function (index, row) {
                            row.editing = false;
                            $(this).datagrid('refreshRow', index);
                           },
                           onCancelEdit: function (index, row) {
                             row.editing = false;
                             $(this).datagrid('refreshRow', index);
                         },
                        frozenColumns: [[
                         /*开启CheckBox选择功能*/
                         { field: 'ck', checkbox: true },
                         { 
                            field: '_operate1',
                            title:'@Html.L("Command")',
                            width: 85,
                            sortable: false,
                            resizable: true,
                            formatter: function showdetailsformatter(value, row, index) {
                                        if (!row.editing) {
                                             return '<div class="btn-group">\
                                                         <button onclick="showDetailsWindow(\'' + row.ID + '\',\'' + JSON.stringify(row).replace(/\"/g, '&quot;') + '\',' + index +')" class="btn btn-default btn-xs" title="查看明细" ><i class="fa fa-pencil-square-o"></i> </button>\
                                                         <button onclick="deleteRow(\'' + row.ID + '\',\'' + JSON.stringify(row).replace(/\"/g, '&quot;') + '\',' + index +')" class="btn btn-default btn-xs" title="删除记录" ><i class="fa fa-trash-o"></i> </button>\
                                                      </div>';
                                         } else {
                                              return '<button class="btn btn-default btn-xs" disabled title="查看明细"  ><i class="fa fa-pencil-square-o"></i> </button>';
                                         }
                                     }
                          }
                        ]],
                        columns: [[
		     { /*ID*/
               field:'ID',
               title:'<span class="required">@Html.DisplayNameFor(model => model.ID)</span>', 
               width:120 ,
               sortable:true,
               resizable:true, 
               hidden:true
              },
			{    /*供应商代码*/
                 field:'SUPPLIERCODE', 
                 title:'<span class="required">@Html.DisplayNameFor(model => model.SUPPLIERCODE)</span>', 
                 width:130,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.SUPPLIERCODE)',required:true, validType: 'length[0,20]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{    /*供应商名称*/
                 field:'SUPPLIERNAME', 
                 title:'<span class="required">@Html.DisplayNameFor(model => model.SUPPLIERNAME)</span>', 
                 width:260,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.SUPPLIERNAME)',required:true, validType: 'length[0,80]' }  
                       },
                 sortable:true,
                 resizable:true 
                          },
      {    /*邮件地址*/
                 field:'EMAIL', 
                 title:'@Html.DisplayNameFor(model => model.EMAIL)', 
                 width:130,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.EMAIL)',required:false, validType: 'length[0,20]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{  /*是否禁用*/
               field:'ISDISABLED', 
               title:'<span class="required">@Html.DisplayNameFor(model => model.ISDISABLED)</span>', 
               width:120, 
               align:'center',
               hidden:false,
               editor:{
                      type:'booleaneditor',
                      options:{
                                 prompt:'@Html.DisplayNameFor(model => model.ISDISABLED)', 
                                 required:true
                               } 
                      },
                formatter:booleanformatter,
                sortable:true, 
                resizable:true 
			},
			{    /*收货地址1*/
                 field:'ADDRESS1', 
                 title:'@Html.DisplayNameFor(model => model.ADDRESS1)', 
                 width:260,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.ADDRESS1)',required:false, validType: 'length[0,80]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{    /*收货地址2*/
                 field:'ADDRESS2', 
                 title:'@Html.DisplayNameFor(model => model.ADDRESS2)', 
                 width:260,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.ADDRESS2)',required:false, validType: 'length[0,80]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{    /*联系人*/
                 field:'CONTACT', 
                 title:'@Html.DisplayNameFor(model => model.CONTACT)', 
                 width:130,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.CONTACT)',required:false, validType: 'length[0,20]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			{    /*联系电话*/
                 field:'PHONENUMBER', 
                 title:'@Html.DisplayNameFor(model => model.PHONENUMBER)', 
                 width:130,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.PHONENUMBER)',required:false, validType: 'length[0,20]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
			
			{    /*备注*/
                 field:'NOTES', 
                 title:'@Html.DisplayNameFor(model => model.NOTES)', 
                 width:260,
                 hidden:false,
                 editor:{
                          type:'textbox',
                          options:{ prompt:'@Html.DisplayNameFor(model => model.NOTES)',required:false, validType: 'length[0,80]' }  
                       },
                 sortable:true,
                 resizable:true 
			},
                 ]]
           });

           $dg.datagrid('enableFilter',[
				{   /*ID*/
					  field: 'ID',
					  type: 'numberbox',
					  op:['equal','notequal','less','lessorequal','greater','greaterorequal']
				  },
				{   /*是否禁用*/
					  field: 'ISDISABLED',
					  type: 'booleanfilter'
     			 },
		   ]);
	 });
 
</script>



<!--end popup detailview javascript block -->
<script src="~/Scripts/jquery.filerupload.min.js"></script>
}

 
